<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="referrer" content="never" />
    <meta name="description" content="Django中整合Vue-cli要解决几个问题： 一、前后端代码放在一个项目中，方便维护； 二、Vue-cli本地调试时的接口跨域问题； 三、Vue-cli build后的文件要能直接提交后就能使用，" />
    <meta property="og:description" content="Django中整合Vue-cli要解决几个问题： 一、前后端代码放在一个项目中，方便维护； 二、Vue-cli本地调试时的接口跨域问题； 三、Vue-cli build后的文件要能直接提交后就能使用，" />
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Django中整合Vue-cli，并解决各种路径引用错误和跨域的问题 - Samve - 博客园</title>
    <link id="favicon" rel="shortcut icon" href="//common.cnblogs.com/favicon.svg" type="image/svg+xml" />
    
    <link rel="stylesheet" href="/css/blog-common.min.css?v=cGPZX-91MnVsFpGp_qDIwTwedO-J7MOgyTfTUau0qqk" />
    <link id="MainCss" rel="stylesheet" href="/skins/mountainink/bundle-mountainink.min.css?v=J87U-ocWJ9KtApKHMmdL5wCun-udAA8_AEHqkLSEzBQ" />
    <link type="text/css" rel="stylesheet" href="/css/hljs/cnblogs.css?v=2spjdq1Snjw5rAm9auWVRax8Gb7nftS4ORu-8fQ7JGM" />
    
    <link id="mobile-style" media="only screen and (max-width: 767px)" type="text/css" rel="stylesheet" href="/skins/mountainink/bundle-mountainink-mobile.min.css?v=FbWAojti4hapFp0LXITskgKBeOZgAgZZV3IgLxaJX08" />
    
    <link type="application/rss+xml" rel="alternate" href="https://www.cnblogs.com/samve/rss" />
    <link type="application/rsd+xml" rel="EditURI" href="https://www.cnblogs.com/samve/rsd.xml" />
    <link type="application/wlwmanifest+xml" rel="wlwmanifest" href="https://www.cnblogs.com/samve/wlwmanifest.xml" />
    <script>
        var currentBlogId = 434678;
        var currentBlogApp = 'samve';
        var cb_enable_mathjax = false;
        var isLogined = false;
        var isBlogOwner = false;
        var skinName = 'MountainInk';
        var visitorUserId = '';
        var hasCustomScript = false;
        try {
            if (hasCustomScript && document.referrer && document.referrer.indexOf('baidu.com') >= 0) {
                Object.defineProperty(document, 'referrer', { value: '' });
                Object.defineProperty(Document.prototype, 'referrer', { get: function(){ return ''; } });
            }
        } catch(error) { }
    </script>
        <script>
            var currentPostDateAdded = '2020-07-03 11:03';
        </script>
    <script src="https://common.cnblogs.com/scripts/jquery-2.2.0.min.js"></script>
    <script src="/js/blog-common.min.js?v=movNGMsW6vKcskrZsYaB2rtqtqgVZ4y3ONEE0GANf3U"></script>
    
    
    
     <script type="text/javascript">
        window.codeHighlightEngine = 1
        window.enableCodeLineNumber = false
     </script>
</head>
<body class="skin-mountainink has-navbar">
    <a name="top"></a>
    <div id="top_nav" class="navbar forpc">
        <nav id="nav_main" class="navbar-main">
            <ul id="nav_left" class="navbar-list navbar-left">
                <li class="navbar-branding"><a href="https://www.cnblogs.com/" title="开发者的网上家园"><img src="/images/logo.svg?v=R9M0WmLAIPVydmdzE2keuvnjl-bPR7_35oHqtiBzGsM" alt="博客园Logo" /></a></li>
                <li><a href="/" onclick="ga('send', 'event', 'Link', 'click', 'skin-navbar-sitehome')">首页</a></li>
                <li><a href="https://news.cnblogs.com/" onclick="ga('send', 'event', 'Link', 'click', 'skin-navbar-news')">新闻</a></li>
                <li><a href="https://q.cnblogs.com/" onclick="ga('send', 'event', 'Link', 'click', 'skin-navbar-q')">博问</a></li>
                <li><a id="nav_brandzone" href="https://brands.cnblogs.com/" onclick="ga('send', 'event', 'Link', 'click', 'skin-navbar-brands')">专区</a></li>
                <li><a href="https://ing.cnblogs.com/" onclick="ga('send', 'event', 'Link', 'click', 'skin-navbar-ing')">闪存</a></li>
                <li><a href="https://edu.cnblogs.com/" onclick="ga('send', 'event', 'Link', 'click', 'skin-navbar-edu')">班级</a></li>
            </ul>
            <ul id="nav_right" class="navbar-list navbar-right">
                <li>
                    <form id="zzk_search" class="navbar-search" action="https://zzk.cnblogs.com/s" method="get">
                        <input name="w" id="zzk_search_input" placeholder="代码改变世界" type="text" tabindex="3" />
                        <button type="submit" id="zzk_search_button">
                            <img src="/images/aggsite/search.svg" alt="搜索" />
                        </button>
                    </form>
                </li>
                <li id="navbar_login_status" class="navbar-list">
                    <a class="navbar-user-info navbar-blog" href="https://i.cnblogs.com/EditPosts.aspx?opt=1" alt="写随笔" title="写随笔">
                        <img id="new_post_icon" class="navbar-icon" src="/images/aggsite/newpost.svg" alt="写随笔" />
                    </a>
                    <a id="navblog-myblog-icon" class="navbar-user-info navbar-blog" href="https://passport.cnblogs.com/GetBlogApplyStatus.aspx" alt="我的博客" title="我的博客">
                        <img id="myblog_icon" class="navbar-icon" src="/images/aggsite/myblog.svg" alt="我的博客" />
                    </a>
                    <a class="navbar-user-info navbar-message navbar-icon-wrapper" href="https://msg.cnblogs.com/" alt="短消息" title="短消息">
                        <img id="msg_icon" class="navbar-icon" src="/images/aggsite/message.svg?v=J0WS2P2iPgaIVgXxcAhliw4AFZIpaTWxtdoNAv9eiCA" alt="短消息" />
                        <span id="msg_count" style="display: none"></span>
                    </a>
                    <div id="user_info" class="navbar-user-info dropdown">
                        <a class="dropdown-button" href="https://home.cnblogs.com/">
                            <img id="user_icon" class="navbar-avatar" src="/images/aggsite/avatar-default.svg" alt="用户头像" />
                        </a>
                        <div class="dropdown-menu">
                            <a id="navblog-myblog-text" href="https://passport.cnblogs.com/GetBlogApplyStatus.aspx">我的博客</a>
                            <a href="https://home.cnblogs.com/">我的园子</a>
                            <a href="https://account.cnblogs.com/settings/account">账号设置</a>
                            <a href="javascript:void(0)" id="navbar_lite_mode_toggle" title="简洁模式会使用简洁款皮肤显示所有博客">
    简洁模式 <img id="navbar_lite_mode_on" src="/images/lite-mode-check.svg" class="hide" /><span id="navbar_lite_mode_spinner" class="hide">...</span>
</a>
                            <a href="javascript:void(0)" onclick="account.logout();">退出登录</a>
                        </div>
                    </div>
                    <a class="navbar-anonymous" href="https://account.cnblogs.com/signup/">注册</a>
                    <a class="navbar-anonymous" href="javascript:void(0);" onclick="account.login()">登录</a>
                </li>
            </ul>
        </nav>
    </div>

    
    <!--done-->
<div id="home">
<div id="header">
	<div id="blogTitle">
        <a id="lnkBlogLogo" href="https://www.cnblogs.com/samve/"><img id="blogLogo" src="/skins/custom/images/logo.gif" alt="返回主页" /></a>		
		
<!--done-->
<h1><a id="Header1_HeaderTitle" class="headermaintitle HeaderMainTitle" href="https://www.cnblogs.com/samve/">Samve</a>
</h1>
<h2></h2>




		
	</div><!--end: blogTitle 博客的标题和副标题 -->
	<div id="navigator">
		
<ul id="navList">
<li><a id="blog_nav_sitehome" class="menu" href="https://www.cnblogs.com/">
博客园</a>
</li>
<li>
<a id="blog_nav_myhome" class="menu" href="https://www.cnblogs.com/samve/">
首页</a>
</li>
<li>

<a id="blog_nav_newpost" class="menu" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">
新随笔</a>
</li>
<li>
<a id="blog_nav_contact" class="menu" href="https://msg.cnblogs.com/send/Samve">
联系</a></li>
<li>
<a id="blog_nav_rss" class="menu" href="javascript:void(0)" data-rss="https://www.cnblogs.com/samve/rss/">
订阅</a>
<!--<partial name="./Shared/_XmlLink.cshtml" model="Model" /></li>--></li>
<li>
<a id="blog_nav_admin" class="menu" href="https://i.cnblogs.com/">
管理</a>
</li>
</ul>


		<div class="blogStats">
			<div id="blog_stats_place_holder"><script>loadBlogStats();</script></div>
		</div><!--end: blogStats -->
	</div><!--end: navigator 博客导航栏 -->
</div><!--end: header 头部 -->
<div id="main">
	<div id="mainContent">
	<div class="forFlow">
		<div id="post_detail">
    <!--done-->
    <div id="topics">
        <div class="post">
            <h1 class = "postTitle">
                
<a id="cb_post_title_url" class="postTitle2 vertical-middle" href="https://www.cnblogs.com/samve/p/13233130.html">
    <span>Django中整合Vue-cli，并解决各种路径引用错误和跨域的问题</span>
    



</a>

            </h1>
            <div class="clear"></div>
            <div class="postBody">
                <div id="cnblogs_post_body" class="blogpost-body blogpost-body-html">
<p>Django中整合Vue-cli要解决几个问题：</p>
<p>一、前后端代码放在一个项目中，方便维护；</p>
<p>二、Vue-cli本地调试时的接口跨域问题；</p>
<p>三、Vue-cli build后的文件要能直接提交后就能使用，不需要再去手动修改其中引用文件的路径后才能提交。</p>
<p>步骤：</p>
<p>一、在目录demo7下新建Django项目；</p>
<p>参考：<a href="https://blog.csdn.net/duansamve/article/details/95866997" data-cke-saved-href="https://blog.csdn.net/duansamve/article/details/95866997">https://blog.csdn.net/duansamve/article/details/95866997</a></p>
<p>二、在目录demo7下建立子目录vue，再在该目录下搭建vue-cli项目；</p>
<p>参考：<a href="https://blog.csdn.net/duansamve/article/details/80466922" data-cke-saved-href="https://blog.csdn.net/duansamve/article/details/80466922">https://blog.csdn.net/duansamve/article/details/80466922</a></p>
<p>Django和Vue-cli搭建完成后的目录结构如下：</p>
<p><span class="cke_widget_wrapper cke_widget_inline cke_widget_image cke_image_nocaption cke_widget_selected" data-cke-widget-wrapper="1" data-cke-filter="off" data-cke-display-name="图像" data-cke-widget-id="3"><img src="https://img-blog.csdnimg.cn/20200703225732940.PNG" alt="" width="258" height="600" class="cke_widget_element" data-cke-saved-src="https://img-blog.csdnimg.cn/20200703225732940.PNG" data-cke-widget-data="{&amp;quot;hasCaption&amp;quot;:false,&amp;quot;src&amp;quot;:&amp;quot;https://img-blog.csdnimg.cn/20200703225732940.PNG&amp;quot;,&amp;quot;alt&amp;quot;:&amp;quot;&amp;quot;,&amp;quot;width&amp;quot;:&amp;quot;258&amp;quot;,&amp;quot;height&amp;quot;:&amp;quot;600&amp;quot;,&amp;quot;lock&amp;quot;:true,&amp;quot;align&amp;quot;:&amp;quot;none&amp;quot;,&amp;quot;classes&amp;quot;:[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="image"><span class="cke_reset cke_widget_drag_handler_container"><img src="" width="15" height="15" class="cke_reset cke_widget_drag_handler" title="点击并拖拽以移动" data-cke-widget-drag-handler="1"><span class="cke_image_resizer" title="点击并拖拽以改变尺寸">​</span></span></span></p>
<p>三、将Django的TEMPLATES目录指向Vue构建后的dist目录：</p>
<p>demo7/demo7/setting.py</p>
<div class="cke_widget_wrapper cke_widget_block cke_widget_codeSnippet cke_widget_selected" data-cke-widget-wrapper="1" data-cke-filter="off" data-cke-display-name="代码段" data-cke-widget-id="2">
<pre class="cke_widget_element" data-cke-widget-data="{&amp;quot;lang&amp;quot;:&amp;quot;python&amp;quot;,&amp;quot;code&amp;quot;:&amp;quot;TEMPLATES = [\n    {\n        'BACKEND': 'django.template.backends.django.DjangoTemplates',\n        'DIRS': ['vue/dist'],\n        'APP_DIRS': True,\n        'OPTIONS': {\n            'context_processors': [\n                'django.template.context_processors.debug',\n                'django.template.context_processors.request',\n                'django.contrib.auth.context_processors.auth',\n                'django.contrib.messages.context_processors.messages',\n            ],\n        },\n    },\n]&amp;quot;,&amp;quot;classes&amp;quot;:[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet"><code class="language-python hljs">TEMPLATES = [
    {
        <span class="hljs-string">'BACKEND': <span class="hljs-string">'django.template.backends.django.DjangoTemplates',
        <span class="hljs-string">'DIRS': [<span class="hljs-string">'vue/dist'],
        <span class="hljs-string">'APP_DIRS': <span class="hljs-keyword">True,
        <span class="hljs-string">'OPTIONS': {
            <span class="hljs-string">'context_processors': [
                <span class="hljs-string">'django.template.context_processors.debug',
                <span class="hljs-string">'django.template.context_processors.request',
                <span class="hljs-string">'django.contrib.auth.context_processors.auth',
                <span class="hljs-string">'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]</span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<span class="cke_reset cke_widget_drag_handler_container"><img src="" width="15" height="15" class="cke_reset cke_widget_drag_handler" title="点击并拖拽以移动" data-cke-widget-drag-handler="1"></span></div>
<p>四、将Django的静态文件夹目录指向Vue构建后的dist目录下的static目录：</p>
<p>demo7/demo7/setting.py</p>
<div class="cke_widget_wrapper cke_widget_block cke_widget_codeSnippet cke_widget_selected" data-cke-widget-wrapper="1" data-cke-filter="off" data-cke-display-name="代码段" data-cke-widget-id="1">
<pre class="cke_widget_element" data-cke-widget-data="{&amp;quot;lang&amp;quot;:&amp;quot;python&amp;quot;,&amp;quot;code&amp;quot;:&amp;quot;# Add for vuejs\n\nSTATICFILES_DIRS = [ \n    os.path.join(BASE_DIR, \&amp;quot;vue/dist/static\&amp;quot;), \n]&amp;quot;,&amp;quot;classes&amp;quot;:[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet"><code class="language-python hljs"><span class="hljs-comment"># Add for vuejs

STATICFILES_DIRS = [ 
    os.path.join(BASE_DIR, <span class="hljs-string">"vue/dist/static"), 
]</span></span></code></pre>
<span class="cke_reset cke_widget_drag_handler_container"><img src="" width="15" height="15" class="cke_reset cke_widget_drag_handler" title="点击并拖拽以移动" data-cke-widget-drag-handler="1"></span></div>
<p>五、将项目的访问路径指定为根路径：</p>
<p>demo7/demo7/urls.py</p>
<div class="cke_widget_wrapper cke_widget_block cke_widget_codeSnippet cke_widget_selected" data-cke-widget-wrapper="1" data-cke-filter="off" data-cke-display-name="代码段" data-cke-widget-id="0">
<pre class="cke_widget_element" data-cke-widget-data="{&amp;quot;lang&amp;quot;:&amp;quot;python&amp;quot;,&amp;quot;code&amp;quot;:&amp;quot;from django.urls import path, include\nfrom django.views.generic.base import TemplateView\n\nurlpatterns = [\n    path('', TemplateView.as_view(template_name=\&amp;quot;index.html\&amp;quot;))\n]&amp;quot;,&amp;quot;classes&amp;quot;:[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet"><code class="language-python hljs"><span class="hljs-keyword">from django.urls <span class="hljs-keyword">import path, include
<span class="hljs-keyword">from django.views.generic.base <span class="hljs-keyword">import TemplateView

urlpatterns = [
    path(<span class="hljs-string">'', TemplateView.as_view(template_name=<span class="hljs-string">"index.html"))
]</span></span></span></span></span></span></code></pre>
<span class="cke_reset cke_widget_drag_handler_container"><img src="" width="15" height="15" class="cke_reset cke_widget_drag_handler" title="点击并拖拽以移动" data-cke-widget-drag-handler="1"></span></div>
<p>&nbsp;六、解决vue-cli构建后的index.html找不到图标和引用的js、css文件路径错误的问题：</p>
<p>参考<a href="https://blog.csdn.net/duansamve/article/details/107116031" data-cke-saved-href="https://blog.csdn.net/duansamve/article/details/107116031">https://blog.csdn.net/duansamve/article/details/107116031</a></p>
<p>七、解决vue-cli接口访问跨域的问题，以方便本地调试，这里采用webpack中配置代理的方法：</p>
<p>参考：<a href="https://blog.csdn.net/duansamve/article/details/90310911" data-cke-saved-href="https://blog.csdn.net/duansamve/article/details/90310911">https://blog.csdn.net/duansamve/article/details/90310911</a></p>
<p>通过以上配置后，前端就可以直接在本地开发调试，开发完后把接口名称批量改正，然后build后就可以直接提交了。</p>
</div>
<div class="clear"></div>
<div id="blog_post_info_block">
    <div id="blog_post_info"></div>
    <div class="clear"></div>
    <div id="post_next_prev"></div>
</div>
            </div>
            <div class="postDesc">posted @ 
<span id="post-date">2020-07-03 23:03</span>&nbsp;
<a href="https://www.cnblogs.com/samve/">Samve</a>&nbsp;
阅读(<span id="post_view_count">263</span>)&nbsp;
评论(<span id="post_comment_count">0</span>)&nbsp;
<a href="https://i.cnblogs.com/EditPosts.aspx?postid=13233130" rel="nofollow">编辑</a>&nbsp;
<a href="javascript:void(0)" onclick="AddToWz(13233130);return false;">收藏</a>&nbsp;
<a href="javascript:void(0)" onclick="reportManager.report({ currentUserId: '', targetType: 'blogPost', targetId: '13233130', targetLink: 'https://www.cnblogs.com/samve/p/13233130.html', title: 'Django中整合Vue-cli，并解决各种路径引用错误和跨域的问题' })">举报</a></div>
        </div>
	    
	    
    </div><!--end: topics 文章、评论容器-->
</div>

<script src="https://common.cnblogs.com/highlight/10.3.1/highlight.min.js" async onload="markdown_highlight()"></script>
<script>
    var allowComments = true, cb_blogId = 434678, cb_blogApp = 'samve', cb_blogUserGuid = '9b7c9077-0565-480d-49db-08d5b61b6fbd';
    var cb_entryId = 13233130, cb_entryCreatedDate = '2020-07-03 23:03', cb_postType = 1;
    updatePostStats(
        [cb_entryId],
        function(id, count) { $("#post_view_count").text(count) },
        function(id, count) { $("#post_comment_count").text(count) })
    zoomManager.apply("#cnblogs_post_body img:not(.code_img_closed):not(.code_img_opened)");
</script>

<a name="!comments"></a>
<div id="blog-comments-placeholder"></div>
<div id="comment_form" class="commentform">
    <a name="commentform"></a>
    <div id="divCommentShow"></div>
    <div id="comment_nav"><span id="span_refresh_tips"></span><a href="javascript:void(0);" onclick="return RefreshCommentList();" id="lnk_RefreshComments" runat="server" clientidmode="Static">刷新评论</a><a href="#" onclick="return RefreshPage();">刷新页面</a><a href="#top">返回顶部</a></div>
    <div id="comment_form_container"></div>
    <div class="ad_text_commentbox" id="ad_text_under_commentbox"></div>
    <div id="ad_t2"></div>
    <div id="opt_under_post"></div>
    <div id="cnblogs_c1" class="under-post-card">
             <a onclick="ga('send', 'event', 'Link', 'click', 'Pangle-C1')" target="_blank" rel="nofollow" href="https://c.gridsumdissector.com/r/?gid=gad_545_ph4hkwzt&ck=32&adk=442&autorefresh=__AUTOREFRESH__">
                <img style="width: 300px; height: 250px;" src="https://img2020.cnblogs.com/blog/35695/202108/35695-20210817131346802-930113090.jpg" alt="" onload="gscmdImpress()" />
             </a>
    </div>
    <div id="under_post_card1"></div>
    <div id="under_post_card2"></div>
    <div id="HistoryToday" class="under-post-card"></div>
    <script type="text/javascript">
       var commentManager = new blogCommentManager();
       commentManager.renderComments(0);
       fixPostBody();
       deliverBigBanner();
setTimeout(function() { incrementViewCount(cb_entryId); }, 50);       deliverT2();
       deliverC1C2();
       loadNewsAndKb();
LoadPostCategoriesTags(cb_blogId, cb_entryId);       LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
       GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate, cb_postType);
       loadOptUnderPost();
       GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);
    </script>
</div>

	</div><!--end: forFlow -->
	</div><!--end: mainContent 主体内容容器-->
	<div id="sideBar">
		<div id="sideBarMain">
			<div id="sidebar_news" class="newsItem">
            <script>loadBlogNews();</script>
</div>
<div id="sidebar_c3"></div>
			<div id="blog-calendar" style="display:none"></div><script>loadBlogDefaultCalendar();</script>			
			<div id="leftcontentcontainer">
				<div id="blog-sidecolumn"></div>
                    <script>loadBlogSideColumn();</script>
			</div>			
		</div><!--end: sideBarMain -->
	</div><!--end: sideBar 侧边栏容器 -->
	<div class="clear"></div>
	</div><!--end: main -->
	<div class="clear"></div>
	<div id="footer">
		<!--done-->
Copyright &copy; 2021 Samve
<br /><span id="poweredby">Powered by .NET 5.0 on Kubernetes</span>



	</div><!--end: footer -->
</div><!--end: home 自定义的最大容器 -->


    

    <input type="hidden" id="antiforgery_token" value="CfDJ8NACB8VE9qlHm6Ujjqxvg5DerKksiLMcg76sD5oufIloa8PfOrdpOZuE7bpdDYv9KLH8RDieMIidkoS54qHpORsCgQIizi3ov1wl98n7S7kWJUJsrijB2-1eXOUv6yLsPDr5R8aqEpmPJji-5l2Flm8" />
</body>
</html>
